package com.googlecode.contests_repo.servlets;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.contests_repo.core.config.ConfigurationManager;

/**
 * Servlet for deleting a given file or folder from the repository.
 */
@WebServlet("/delete_file")
public class DeleteFileServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String resourcePath = URLDecoder.decode(request.getParameter("path"), "UTF-8");
		String repoRoot = ConfigurationManager.getInstance().getRepoRoot();
		File file = new File(repoRoot + File.separator + resourcePath);
		File parentFile = file.getParentFile();

		boolean success = deleteRecursive(file);

		response.sendRedirect("view_folder.jsp?path="
				+ parentFile.getPath().substring(repoRoot.length())
				+ "&deleteSuccessful=" + success);
	}

	private boolean deleteRecursive(File file) {
		if (file.isDirectory()) {
			for (File child : file.listFiles()) {
				boolean success = deleteRecursive(child);
				if (!success) {
					return false;
				}
			}
		}

		return file.delete();
	}
}
